package com.dq.rbac.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dq.rbac.entity.SysMenu;
import com.dq.rbac.entity.SysRole;
import com.dq.rbac.entity.SysUser;
import com.dq.rbac.mapper.SysMenuMapper;
import com.dq.rbac.mapper.SysRoleMapper;
import com.dq.rbac.service.SysUserService;
import com.dq.rbac.mapper.SysUserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * (SysUser)表服务实现类
 *
 * @author Dq
 * @since 2022-12-26 12:58:58
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysMenuMapper menuMapper;

    @Override
    public SysUser getByUserName(String username) {
        SysUser user = getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
        return user;
    }

    //最重要的部分
    @Override
    public String getUserAuthorityInfo(Long userId) {
        //拼接权限
        StringBuilder authority = new StringBuilder();
        //根据用户id获取所有的角色信息
        //  SELECT * from sys_role where id IN (SELECT role_id FROM sys_user_role WHERE user_id = 1)
        List<SysRole> roleList = roleMapper.selectList(new LambdaQueryWrapper<SysRole>()
                .inSql(SysRole::getId, "SELECT role_id FROM sys_user_role WHERE user_id = " + userId));
        if (roleList.size() > 0) {
            String userRoleListStr = roleList.stream().map(role -> "ROLE_" + role.getCode()).collect(Collectors.joining(","));
            authority.append(userRoleListStr);
        }
        //遍历所有角色货期所有菜单权限，而且不重复
        Set<String> menuSet = new HashSet<>();
        for (SysRole sysRole : roleList) {
            //SELECT * from sys_menu where id IN (SELECT menu_id FROM sys_role_menu WHERE role_id = 1)
            List<SysMenu> userMenuList = menuMapper.selectList(new LambdaQueryWrapper<SysMenu>().inSql(SysMenu::getId, "SELECT menu_id FROM sys_role_menu WHERE role_id = " + sysRole.getId()));
            for (SysMenu sysMenu : userMenuList) {
                String perms = sysMenu.getPerms();
                if (StrUtil.isNotEmpty(perms)) {
                    menuSet.add(perms);
                }
            }
        }
        if (menuSet.size() > 0) {
            authority.append(",");
            String menuSetStr = menuSet.stream().collect(Collectors.joining(","));
            authority.append(menuSetStr);
        }
        log.info("用户权限列表串 ---{}", authority.toString());
        return authority.toString();
    }

}